<?php


namespace app\api\controller\v1;


use app\api\controller\v1\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use fast\Http;
use other\Rsa;
use think\Db;

/**
 * 诚代信息
 */
class ChengDaiXinXi
{
    private $wxapp_id='10004';
    private $channel_id='48';


    public function pushClue($mapping, $clue_info, $listPush)
    {

        $apiName = '【' . $mapping['api_name'] . '】';

//        $clue_info['clue_name']='测试张';
//        $clue_info['phone']='13000000004';

        $this->getValidate($apiName,$clue_info); // 手机号码的撞库

        $clue_rule = json_decode($mapping['rule_json'], true);
        $params = [];
        if (!$clue_rule) {
            $errMsg = $apiName . '读取商户接收规则失败';
            ClueErrorLog::record($clue_info['clue_id'], $errMsg, $clue_info);
            model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        } else {

            foreach ($clue_rule as $v) {
                $params[$v['curr']] = $clue_info[$v['orig']];
                if ($v['orig'] == 'city') {
                    $citys = explode('-', $clue_info[$v['orig']]);
                    $city_info = Db::name('city')->where(['type' => 2, 'id' => $citys[1]])->find();
                    $params[$v['curr']] = $city_info['name'];
                }
            }

            if (!empty($clue_info['show_city'])) {
                if (strpos($clue_info['show_city'], '-') !== false) {
                    $city_t = explode('-', $clue_info['show_city']);
                    if (count($city_t) == 3) {
                        $params['city'] = $city_t[1];
                    } elseif (count($city_t) == 2) {
                        $params['city'] = $city_t[1];
                    } elseif (count($city_t) == 1) {
                        $params['city'] = $city_t[0];
                    }
                }else{
                    $params['city']=$clue_info['show_city'];
                }
            }

            if(strpos($clue_info['apply_limit'], '-') !== false){
                $moneyArr=explode('-',$clue_info['apply_limit']);
                $moneyNum=count($moneyArr);
                if($moneyNum==1){
                    $MoneyStr=$moneyArr[0];
                }else{
                    $MoneyStr=$moneyArr[1];
                }
            }else{
                $MoneyStr=$clue_info['apply_limit'];
            }

            if(strpos($MoneyStr, '万') !== false){
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $params['loans_price']=$MoneyStr*10000;
            }else{
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $params['loans_price']=intval($MoneyStr);
            }

            if($params['sex']==0){
                $params['sex']='1';
            }

            $params['wxapp_id']=$this->wxapp_id;
            $params['channel_id']=$this->channel_id;
            $params['s']='/api/index/add';


            $params['property']='3';
            $params['vehicle']='2';
            $params['guarantee']='2';
            $params['drop']='2';
            $params['credit_card']='2';
            $params['social']='2';
            $params['fund']='2';

            $remarkStr='';

            //渠道

//            if(!empty($clue_info['push_channel'])){
//                $source=$clue_info['push_channel'];
//            }else{
//                $advInfo=Db::name('account')->where('adv_id',$clue_info['adv_id'])->find();
//                $source=$advInfo['show_channel'];
//                if(empty($source)){
//                    $source=get_channel_desc($clue_info['type']);
//
//                }
//            }
//            $remarkStr.=$source.'-';


            if($clue_info['pro_id']==3){
                $params['property']='1';
//                $remarkStr.='有房-';
            }elseif ($clue_info['pro_id']==4){
                $params['vehicle']='1';
//                $remarkStr.='有车-';
            }elseif ($clue_info['pro_id']==6){
                $params['fund']='1';
//                $remarkStr.='有公积金-';
            }else{
                $errMsg=$apiName.'线索推送商户处理失败贷款类型不符';
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$params);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }

//            if(empty($clue_info['remark'])){
//            }else{
//                $remark=json_decode($clue_info['remark'],true);
//                if (is_array($remark)){
//                    $remarkArr=[];
//                    $keys=array_keys($remark);
//                    $b=false;//默认索引
//                    //判断关联数组还是索引数组
//                    foreach($keys as $value){
//                        if(!is_int($value)){
//                            $b=true;
//                            break;
//                        }
//                    }
//                    //是关联数组
//                    if($b){
//                        foreach ($remark as $kk=>$vv){
//                            if(strpos($kk, '城市') !== false){
//                            }else{
//                                $remarkArr[]=$vv;
//                            }
//                        }
//                    }else{
//                        foreach ($remark as $vv){
//                            if($clue_info['type']==1){
//                                if(strpos($vv['name'], '城市') !== false){
//                                }else{
//                                    $remarkArr[]=$vv['value'];
//                                }
//                            }else{
//                                if(isset($vv['name'])&&isset($vv['value'])){
//                                    if(strpos($vv['name'], '城市') !== false){
//                                    }else{
//                                        $remarkArr[]=$vv['value'];
//                                    }
//                                }else{
//                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
//                                }
//                            }
//                        }
//                    }
//                }else{
//                    $remarkArr[]=$remark;
//                }
//                $remarkStr=$remarkStr.implode('|',$remarkArr);
//            }
//
//            $params['comment']=$remarkStr;

//            if(!$params['age']){
//                unset($params['age']);
//            }

            $api_url = $mapping['api_url'];

//            $api_url.='?'.http_build_query($params);



//            dump($api_url);

//            dump($params);


            $postData=$params;



            $res_json = $this->getJson($api_url, $params);
//           dump($res_json);
            $res = json_decode($res_json, true);
//            dump($res);die;
            if (!empty($res)) {
                $res['params'] = $postData;
                if ($res['code'] != 1) {
                    $errMsg = $apiName . '线索推送商户处理失败：' . $res['msg'];
                    ClueErrorLog::record($clue_info['clue_id'], $errMsg, $res);
                    model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
                    throw new ParamException(['msg' => $errMsg, 'errorCode' => 10001]);
                }
            } else {
                $errMsg = $apiName . '线索推送商户请求失败';
                ClueErrorLog::record($clue_info['clue_id'], $errMsg, $postData);
                model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
                throw new ParamException(['msg' => $errMsg, 'errorCode' => 10001]);
            }
            return $res;
        }
    }

//    private function getSign($data){
//        $data['appkey']=$this->appKey;
//
////        dump($data);
//        ksort($data);
//
////        dump($data);
//
//        // 生成url的形式
////    $str = http_build_query($data, null, '&', PHP_QUERY_RFC3986);
//
//        $str = '';
//        foreach ($data as $key => $value) {
//            $str .= $key . '=' . $value . '&';
//        }
//        $str = trim($str, '&');
//        // 生成sign
////        $signStr = $str . '&key=' . $token;
////    dump($str);
//        return sha1($str);
//    }


    function generateSignature(array $data): string {
        ksort($data); // 按照数组key进行升序排序

        $string = '';
        foreach ($data as $key => $value) {
            $string .= $key . '=' . $value . '&';
        }
        $string = rtrim($string, '&'); // 去除最后一个多余的&符号


        $signature = strtoupper(md5($string)); // 进行md5加密并转换为大写形式

        return $signature;
    }

//可以直接用
    public function getValidate($apiName,$clue_info)
    {
        $phone=$clue_info['phone'];
        $api_url = 'http://39.107.72.183:8001/index.php';

        $api_params = [
            's'=>'/api/index/check_mobile',
            'wxapp_id'=>'10004',
            'mobile'=>md5($phone),
        ];



//        $api_url.='?'.http_build_query($api_params);
//        dump($api_url);

        $res_json = $this->getJson($api_url, $api_params);
//        dump($res_json);
        $res  = json_decode($res_json, true);
//        dump($res);
//        die;
        if(!empty($res)){
            if($res['code']!==0){
                $errMsg=$apiName.'CRM手机号码的撞库失败：'.$res['msg'];
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }else{
//                if($res['data']['phoneMd5Exist']){
//                    if(empty($clue_info['is_find'])&&!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city']){
//                        $clue_info['city'] = $clue_info['clue_city'];
//                        $clue_info['next_city'] = $clue_info['clue_city'];
//                        $listPush[]=$clue_info['push_id'];
//                        $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                        if($clueRes['code']!=200){
//                            $errMsg=$clueRes['msg'];
//                            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                        }
//                    }else{
//                        $errMsg=$apiName.'CRM手机号码的撞库重复';
//                        ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                        model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                        $isRe=Db::name('clue_err_log')->where(['type'=>2,'adv_id'=>$clue_info['adv_id'],'pro_id'=>$clue_info['pro_id'],'clue_id'=>$clue_info['id']])->find();
//                        if(empty($isRe)){
//                            Db::name('clue_err_log')->insert([
//                                'type'=>2,
//                                'clue_id'=>$clue_info['id'],
//                                'adv_id'=>$clue_info['adv_id'],
//                                'pro_id'=>$clue_info['pro_id'],
//                                'city'=>$clue_info['city'],
//                                'create_time'=>time()]);
//                        }
//                        if(empty($clue_info['is_find'])){
//                            $listPush[]=$clue_info['push_id'];
//                            $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                            if($clueRes['code']!=200){
//                                $errMsg=$clueRes['msg'];
//                                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                            }
//                        }else{
//                            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                        }
//                    }
//                }
            }
        }else{
            $errMsg=$apiName.'CRM手机号码的撞库请求失败';
            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        }
        return $res;
    }

    /**
     * post发送json格式的数据
     */
    public function postJson($url, $data)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            throw new ParamException(['msg' => '请求数据不能为空', 'errorCode' => 10000]);
        }
        $params = json_encode($data, JSON_UNESCAPED_UNICODE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        curl_setopt($curl, CURLOPT_HEADER, 0);
//        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//            'Content-Type: application/json; charset=utf-8',
//        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        //writelog("请求日志".$params. "====". $res. "====". $url);
        return $res;
    }

    public function postData($url, $data)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            throw new ParamException(['msg' => '请求数据不能为空', 'errorCode' => 10000]);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
//        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//            'Content-Type: application/json; charset=utf-8',
//        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        //writelog("请求日志".$params. "====". $res. "====". $url);
        return $res;
    }

    public function getUrl($url,$data){
        $str = $url.'?';
        foreach ($data as $key => $value) {
            $str .= $key . '=' . $value . '&';
        }
        $str = trim($str, '&');
        return $str;
    }

    public function getJson($url,$data){


        $curl = curl_init();

        $url=$this->getUrl($url,$data);
//        dump($url);
//        die;

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            throw new ParamException(['msg' => '请求数据不能为空', 'errorCode' => 10000]);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        //writelog("请求日志".$params. "====". $res. "====". $url);
        return $res;


    }



}